<script setup lang="ts">
import CategoryTreeView from '@/views/commodity/CategoryTreeView.vue'
import { nextTick, reactive, ref } from 'vue'
import type { FormInstance, FormRules, TableInstance } from 'element-plus'
import type { AttrGroupVo, PageNationParams } from '@/api/attr-group/type'
import type { CategoryVo } from '@/api/category/type'
import {
  addAttrGroupRequest,
  deleteAttrGroupRequest,
  getAttrGroupByIdRequest,
  pageNationRequest,
  updateAttrGroupRequest,
} from '@/api/attr-group'
import { useUserStore } from '@/stores/userStore'

// 分类id
const categoryID = ref<number>()
// 分页查询参数
const pageNationParams = ref<PageNationParams>({
  pageIndex: 1,
  pageSize: 5,
  condition: '',
  catalogID: 0,
})
// 当前页码
const currentPage = ref<number>(1)
// 每页条数
const pageSize = ref<number>(5)
// 改变每页系数单击事件
const handleSizeChange = async () => {
  pageNationParams.value.pageIndex = 1
  pageNationParams.value.pageSize = pageSize.value
  await pageNationQuery(pageNationParams.value)
}
// 改变当前页码单击事件
const handleCurrentChange = async () => {
  pageNationParams.value.pageIndex = currentPage.value
  await pageNationQuery(pageNationParams.value)
}
// 查询属性分组
const queryAttrGroup = async (data: number) => {
  categoryID.value = data
  ;(pageNationParams.value.pageIndex = 1),
    (pageNationParams.value.pageSize = 5),
    (pageNationParams.value.catalogID = categoryID.value)
  await pageNationQuery(pageNationParams.value)
}
// 属性分组集合
let attrGroupVos = ref<AttrGroupVo[]>([])
// 总条数
let count = ref<number>()
// 搜索条件
let searchCondition = ref<string>('')
// 分页查询属性分组
const pageNationQuery = async (pageNationParams: PageNationParams) => {
  await pageNationRequest(pageNationParams)
    .then((res) => ((attrGroupVos.value = res.items), (count.value = res.count)))
    .catch((err) => console.log(err))
}
// 属性分组对象
let attrGroupVo = ref<AttrGroupVo>({
  attrGroupID: 0,
  attrGroupName: '',
  sort: undefined,
  description: '',
  icon: '',
  catalogID: 0,
  catalogName: '',
  idPath: [],
})
// 控制新增及修改对话框的开启和隐藏;true-开房;false-隐藏
const dialogVisible = ref(false)
// 分类集合
const categoryVos = ref<CategoryVo[]>([])
// 查询分类信息
const getCategoryVos = (data) => {
  categoryVos.value = data
}
// 添加或修改属性分组
const addOrUpdateAttrGroup = () => {
  dialogVisible.value = true
  attrGroupVo = ref<AttrGroupVo>({
    attrGroupID: 0,
    attrGroupName: '',
    sort: undefined,
    description: '',
    icon: '',
    catalogID: undefined,
    catalogName: '',
    idPath: [],
  })
  // 清除校验信息
  nextTick(() => {
    addAttrGroupRef.value.clearValidate('attrGroupName')
    addAttrGroupRef.value.clearValidate('sort')
    addAttrGroupRef.value.clearValidate('description')
    addAttrGroupRef.value.clearValidate('icon')
    addAttrGroupRef.value.clearValidate('catalogID')
  })
}

// 级联选择器属性
const prop = { value: 'categoryID', label: 'name', children: 'children' }
// 添加和修改属性分组表单实例
const addAttrGroupRef = ref<FormInstance>()
// 排序字段校验规则
const validateSort = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入排序'))
  } else if (value < 0 || !Number.isInteger(Number(value))) {
    callback(new Error('排序必须为非负整数'))
  } else {
    callback()
  }
}
// 分类id校验规则
const validateCatalogID = (rule, value, callback) => {
  if (attrGroupVo.value.catalogID === 0) {
    callback(new Error('请输入所属分类'))
  }
  callback()
}
// 校验对话框规则
const addRules = reactive<FormRules<AttrGroupVo>>({
  attrGroupName: [
    { required: true, message: '请输入属性分组名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50之间', trigger: 'change' },
  ],
  sort: [{ required: true, validator: validateSort, trigger: 'blur' }],
  description: [
    { required: true, message: '请输入属性分组名称', trigger: 'blur' },
    { min: 2, max: 255, message: '长度在2到255之间', trigger: 'change' },
  ],
  icon: [
    { required: true, message: '请输入组图标', trigger: 'blur' },
    { max: 5, message: '长度在1到5之间', trigger: 'change' },
  ],
  catalogID: [{ required: true, validator: validateCatalogID, trigger: 'blur' }],
})
// 确定按钮单击事件
const saveAttrGroup = () => {
  attrGroupVo.value.catalogID = attrGroupVo.value.catalogID[2]
  addAttrGroupRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // atrGroupID为0，则发送新增请求
      if (attrGroupVo.value.attrGroupID === 0) {
        await addAttrGroupRequest(attrGroupVo.value)
          .then((res) => {
            dialogVisible.value = false
            pageNationQuery(pageNationParams.value)
          })
          .catch((err) => console.log(err))
      } else {
        // atrGroupID不为0，则发送更新请求
        await updateAttrGroupRequest(attrGroupVo.value)
          .then((res) => {
            dialogVisible.value = false
            pageNationQuery(pageNationParams.value)
          })
          .catch((err) => console.log(err))
      }
    }
  })
}
// 搜索按钮单击事件
const search = async () => {
  pageNationParams.value.condition = searchCondition.value
  pageNationParams.value.catalogID = 0
  await pageNationQuery(pageNationParams.value)
}
// 引入用户仓库
const userStore = useUserStore()
const buttons = userStore.buttons
const edit = (row) => {
  getAttrGroupByIdRequest(row.attrGroupID).then((res) => {
    Object.assign(attrGroupVo.value, res)
    dialogVisible.value = true
  })
}
// 表格实例
const attrGroupTable = ref<TableInstance>()
// 属性分组id集合
let attrGroupIds: number[] = []
// 删除按钮确定事件
const deleteAttrGroup = async (row) => {
  attrGroupIds.push(row.attrGroupID)
  await deleteAttrGroupRequest(attrGroupIds).then((res) => {
    pageNationQuery(pageNationParams.value)
    attrGroupIds = []
  })
}
// 批量单击事件
const batchDelete = async () => {
  attrGroupTable.value.getSelectionRows().forEach((row) => {
    attrGroupIds.push(row.attrGroupID)
  })
  await deleteAttrGroupRequest(attrGroupIds).then((res) => {
    pageNationQuery(pageNationParams.value)
    attrGroupIds = []
  })
}
// 控制关联窗口的打开与关闭。true-打开；false-关闭
const relationDialogVisible = ref(false)
// 关联按钮单击事件
const editRelation = (row) => {
  relationDialogVisible.value = true
}
</script>

<template>
  <div class="container">
    <el-row>
      <!--      分类树-->
      <el-col :span="6">
        <CategoryTreeView @sendCategoryID="queryAttrGroup" @sendCategoryVos="getCategoryVos" />
      </el-col>
      <!--      属性列表-->
      <el-col :span="18">
        <!--        搜索按钮-->
        <div>
          <el-form inline ref="searchRef">
            <el-form-item>
              <el-input placeholder="组名或描述" v-model="searchCondition"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button @click="search">查询</el-button>
              <el-button type="primary" @click="addOrUpdateAttrGroup">新增</el-button>
              <el-popconfirm title="确定要删除吗?" @confirm="batchDelete">
                <template #reference>
                  <el-button type="danger">批量删除</el-button>
                </template>
              </el-popconfirm>
            </el-form-item>
          </el-form>
        </div>
        <!--        显示属性分组表格-->
        <el-table
          style="width: 100%"
          border
          :data="attrGroupVos"
          show-overflow-tooltip
          ref="attrGroupTable"
        >
          <el-table-column type="selection" align="center" width="50" />
          <el-table-column type="index" label="序号" align="center" width="60" />
          <el-table-column prop="attrGroupName" label="组名" align="center" width="120" />
          <el-table-column prop="sort" label="排序" align="center" width="100" />
          <el-table-column prop="description" label="描述" align="center" width="180" />
          <el-table-column prop="icon" label="组图标" align="center" width="80" />
          <el-table-column prop="catalogName" label="所属分类" align="center" width="120" />
          <el-table-column label="操作" align="center" width="240">
            <template #default="scope">
              <el-button type="success" @click="editRelation(scope.row)">关联</el-button>
              <el-button type="success" @click="edit(scope.row)">修改</el-button>
              <el-popconfirm title="确定要删除吗?" @confirm="deleteAttrGroup(scope.row)">
                <template #reference>
                  <el-button type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20]"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="count"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          style="margin: 1rem 0"
        />
      </el-col>
    </el-row>
    <!--    添加和修改属性分组对话框-->
    <el-dialog v-model="dialogVisible" title="新增属性分组" width="600">
      <el-form ref="addAttrGroupRef" :model="attrGroupVo" label-width="auto" :rules="addRules">
        <el-form-item label="组名" prop="attrGroupName">
          <el-input v-model="attrGroupVo.attrGroupName"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="attrGroupVo.sort"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="attrGroupVo.description"></el-input>
        </el-form-item>
        <el-form-item label="组图标" prop="icon">
          <el-input v-model="attrGroupVo.icon"></el-input>
        </el-form-item>
        <el-form-item label="所属分类">
          <el-cascader
            v-model="attrGroupVo.catalogID"
            :options="categoryVos"
            :props="prop"
            filterable
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer" style="margin-top: 1rem">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAttrGroup">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <!--  关联属性对话框-->
    <el-dialog title="关联属性" v-model="relationDialogVisible" style="width: 40rem">
      <el-button style="margin-left: 0">新增关联</el-button>
      <el-table>
        <el-table-column label="序号" type="index" align="center" width="100"></el-table-column>
        <el-table-column label="属性分组" prop="brandName" align="center"></el-table-column>
        <el-table-column label="属性名" prop="brandName" align="center"></el-table-column>
        <el-table-column label="属性值" prop="categoryName" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="danger">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<style scoped>
.container {
  padding: 1rem 0.5rem;
  width: 100%;
}
</style>
